package com.briup.myblog.service.impl;

import com.briup.myblog.aop.LogAspect;
import com.briup.myblog.bean.basic.Article;
import com.briup.myblog.bean.basic.BaseUser;
import com.briup.myblog.dao.ext.ArticleExtMapper;
import com.briup.myblog.dao.ext.LoginMapper;
import com.briup.myblog.dao.ext.UserMapper;
import com.briup.myblog.exception.CustomerException;
import com.briup.myblog.service.IBaseUserService;
import com.briup.myblog.utils.JwtUtil;
import com.briup.myblog.utils.ResultStatus;
import com.briup.myblog.utils.UserInfoUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Slf4j
@Service
public class BaseUserServiceImpl implements IBaseUserService {
    @Autowired
    private UserMapper mapper;
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private ArticleExtMapper articleExtMapper;
    @Autowired
    private ArticleServiceImpl service;
    @Override
    public String login(String username, String password) {
        BaseUser baseUser = loginMapper.selectUserByName(username);
        if (baseUser == null) {
            throw new CustomerException(ResultStatus.USER_NOT_FOUND);
        } else {
            if (!Objects.equals(password, baseUser.getPassword())) {
                throw new CustomerException("密码错误");
            }
            if (baseUser.getStatus() != 0) {
                throw new CustomerException("账号被锁定");
            }
            String id = String.valueOf(baseUser.getUserId());
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("username", baseUser.getUsername());
            userInfo.put("realname", baseUser.getRealname());
            userInfo.put("role", baseUser.getRole());
            return JwtUtil.sign(id, userInfo);
        }
    }

    @Override
    public void addUser(BaseUser user) {
        BaseUser baseUser = mapper.selectUserOnlyByEmail(user.getEmail());
        BaseUser bs = mapper.selectUserByUserName(user.getUsername());
        if(baseUser!=null){
            throw new CustomerException("邮箱与其他用户邮箱相同，请重试！");
        }
        if(bs!=null){
            throw new CustomerException("用户名已被使用，请重试！");
        }
        loginMapper.addUser(user);
    }

    @Override
    public void deleteUserById(Integer id) {
        BaseUser user = mapper.findUserById(id);//根据id查找用户
        List<Article>list = articleExtMapper.findArticleByUserId(id);//根据用户id查找资讯
        if (user == null) {
            throw new CustomerException(ResultStatus.USER_NOT_FOUND);
        } else{
            if(user.getRole()==0){
                throw new CustomerException("无法删除管理员");
            }
            else {
                if(list.size()!=0){//如果用户发布资讯不为空
                    for(int i = 0;i<list.size();i++){//循环删除资讯
                        service.deleteArticleById(list.get(i).getArticleId());
                    }
                }
                mapper.deleteUserById(id);//删除用户
            }

        }

    }

    @Override
    public PageInfo<BaseUser> findUserByPageHelper(Integer role, String username, int pageNum, int pageSize) {
        PageInfo<BaseUser>pageInfo;
        if(role==null){
            if(username==null){
                List<BaseUser>listAll = mapper.selectAllUserByPageHelper();
                pageInfo = new PageInfo<>(listAll);
            }
            else {
                List<BaseUser>listUsername = mapper.selectUserByPageHelperWithUsername(username);//根据用户名模糊搜索
                pageInfo = new PageInfo<>(listUsername);
            }
        }
        else {
            if(username==null){
                List<BaseUser>listRole = mapper.selectUserByPageHelperWithRole(role);//根据角色搜索
                pageInfo = new PageInfo<>(listRole);
            }
            else {
                List<BaseUser> list = mapper.findUserByPageHelper(role, username);//根据角色和用户名搜索
                pageInfo = new PageInfo<>(list);
            }
        }
        return pageInfo;

    }

    @Override
    public void updateUser(BaseUser baseUser) {
        BaseUser user = mapper.findUserById(baseUser.getUserId());//根据id查找用户
        BaseUser bs = mapper.selectUserByEmail(baseUser.getEmail(), baseUser.getUserId());//根据id和邮箱查找用户
        if (user == null) {
            throw new CustomerException(ResultStatus.USER_NOT_FOUND);
        }
        else{
            if(bs==null){
                mapper.updateUserInfoById(baseUser);//更新用户信息
            }
            else {
                throw new CustomerException("邮箱不能与其他用户相同！");
            }
        }

    }

    @Override
    public void updateUserIcon(int id, String alterUserIcon) {
        BaseUser user = mapper.findUserById(id);//根据id查找用户
        if (user == null) {
            throw new CustomerException(ResultStatus.USER_NOT_FOUND);
        } else
            mapper.updateUserIcon(id, alterUserIcon);//更新用户头像信息
    }

    @Override
    public BaseUser currentUserInfo(String token) {
        String userId = JwtUtil.getUserId(token);
        int id = Integer.parseInt(userId);
        BaseUser user = mapper.findUserById(id);
        return user;
    }
}
